﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ZYLFramework.Common;

namespace ZYLFramework.Manage
{
    public class SResources
    {
        public UnityEngine.Object Asset;
        public int Reference { get; private set; }

        public SResources()
        {
            Asset = (Object) null;
            Reference = 0;
        }

        public void AddReference() => Reference++;
        public void SubReference() => Reference--;
    }

    /// <summary>
    /// 资源管理器单例
    /// </summary>
    public class ResourcesManage : MonoSingleton<ResourcesManage>
    {
        /// <summary>
        /// 缓存容器
        /// </summary>
        private Dictionary<string, SResources> ht = new Dictionary<string, SResources>();

        /// <summary>
        /// 卸载资源
        /// </summary>
        /// <param name="path"></param>
        public void UnLoadAsset(string path)
        {
            if (!ht.ContainsKey(path))
            {
                return;
            }
            var sResources = ht[path];
            sResources.SubReference();
            if (sResources.Reference <= 0)
            {
                Resources.UnloadAsset(sResources.Asset);
            }
        }

        /// <summary>
        /// 加载资源
        /// </summary>
        /// <param name="path">资源地址</param>
        public Object LoadAsset(string path)
        {
            if (!ht.ContainsKey(path))
            {
                SResources temp = new SResources(); 
                temp.Asset = Resources.Load(path);
                ht.Add(path,temp);
            }
            ht[path].AddReference();
            return ht[path].Asset;
        }
    
        /// <summary>
        /// 实例化Object资源
        /// </summary>
        /// <param name="path">资源地址</param>
        public Object NewObjectAsset(string path)
        {
            Debug.Log(path);
            if (!ht.ContainsKey(path))
            {
                LoadAsset(path);
            }
            var sResources = ht[path];
            return Instantiate(sResources.Asset);
        }
    }
}